package com.demo3.util;

import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author xiaochi
 * @date 2022/7/21 14:11
 * @desc ElasticSearchUtil
 */
@Component
public class ElasticSearchUtil {

    private static ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    public void setElasticsearchRestTemplate(ElasticsearchRestTemplate elasticsearchRestTemplate) {
        ElasticSearchUtil.elasticsearchRestTemplate = elasticsearchRestTemplate;
    }

    /**
     * 分页查询
     * @param pageNum   当前页
     * @param pageSize  每个数量
     * @param o         搜索对象
     * @param <T>
     * @return
     */
    public static <T>List<T> page(Integer pageNum,Integer pageSize,T o){
        return page(pageNum,pageSize,o, (SortBuilder<?>) null);
    }

    /**
     * 分页查询
     * @param pageNum   当前页
     * @param pageSize  每个数量
     * @param o         搜索对象
     * @param <T>
     * @return
     */
    public static <T>List<T> page(Integer pageNum,Integer pageSize,T o,SortBuilder<?>... sortBuilders){
        NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();
        // searchQueryBuilder.withQuery(QueryBuilders.matchAllQuery());// 没有条件.所有数据
        getFieldValue(o).forEach((k,v) ->searchQueryBuilder.withQuery(QueryBuilders.matchQuery(k,v)));
        if (sortBuilders != null){
            Arrays.stream(sortBuilders).forEach(searchQueryBuilder::withSorts);
        }
        searchQueryBuilder.withPageable(PageRequest.of(pageNum-1,pageSize));// 第一页0开始
        SearchHits<T> searchHits = elasticsearchRestTemplate.search(searchQueryBuilder.build(), (Class<T>) o.getClass());
        return searchHits.getSearchHits().stream().map(SearchHit::getContent).collect(Collectors.toList());
    }

    /**
     * 分页查询
     * @param pageNum      当前页
     * @param pageSize     每个数量
     * @param clazz        class
     * @param queryBuilder 匹配条件的queryBuilder
     * @param <T>
     * @return
     */
    public static <T>List<T> page(Integer pageNum, Integer pageSize, Class<T> clazz, QueryBuilder ...queryBuilder){
        return page(pageNum,pageSize,clazz,null,Arrays.asList(queryBuilder));
    }

    /**
     * 分页查询
     * @param pageNum      当前页
     * @param pageSize     每个数量
     * @param clazz        class
     * @param sortBuilders 排序的sortBuilders
     * @param queryBuilder 匹配条件的queryBuilder
     * @param <T>
     * @return
     */
    public static <T>List<T> page(Integer pageNum, Integer pageSize, Class<T> clazz, SortBuilder<?> sortBuilders, List<QueryBuilder> queryBuilder){
        NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();
        queryBuilder.forEach(searchQueryBuilder::withQuery);
        if (sortBuilders != null){
            searchQueryBuilder.withSorts(sortBuilders);
        }
        searchQueryBuilder.withPageable(PageRequest.of(pageNum-1,pageSize));// 第一页0开始
        SearchHits<T> searchHits = elasticsearchRestTemplate.search(searchQueryBuilder.build(), clazz);
        return searchHits.getSearchHits().stream().map(SearchHit::getContent).collect(Collectors.toList());
    }

    /**
     * 筛选搜索条件字段与值
     * @param o
     * @return
     */
    private static Map<String,Object> getFieldValue(Object o){
        Field[] fields = o.getClass().getDeclaredFields();
        Map<String,Object> map = new HashMap<>();
        for (Field  field : fields){
            String key = field.getName();
            if (!Objects.equals("serialVersionUID",key)){
                Object value = getFieldValueByName(key, o);
                if (null != value && !"".equals(value)){
                    map.put(field.getName(),value);
                }
            }
        }
        return map;
    }

    /**
     * 根据属性名获取属性值
     */
    private static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[] {});
            return method.invoke(o, new Object[] {});
        } catch (Exception e) {
            throw new RuntimeException("根据属性名获取属性值异常："+e.getMessage(),e);
        }
    }
}
